package edu.utility.Gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ImagePanel extends JPanel{
	
	BufferedImage image;
	BufferedImage preview;
	Dimension size = new Dimension();
	public ImagePanel()
	{
		this.setBorder(BorderFactory.createLineBorder(Color.black));
		this.setBounds(20, 70, 230, 100);
		try{
			preview = ImageIO.read(new File("preview.jpg"));
			changeQuality(10);
		}catch(Exception ex){}
	}
	
	public void updateImage(File file){
		try{
			this.image = ImageIO.read(file);
		}catch(Exception ex){
			System.out.println("error");
		}
		repaint();
	}
	
	protected void paintComponent(Graphics g)
	{
		g.drawImage(image, 0, 0, this);
	}
	
	public void changeQuality(int n) throws Exception{
		Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
		ImageWriter writer = (ImageWriter)iter.next();
		ImageWriteParam iwp = writer.getDefaultWriteParam();
		iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
		iwp.setCompressionQuality((float)n/10);
		File f = new File("lowQuality.jpg");
		f.createNewFile();

		FileImageOutputStream output = new FileImageOutputStream(f);
		writer.setOutput(output);
		IIOImage loqQuality = new IIOImage(preview, null, null);
		writer.write(null, loqQuality, iwp);
		writer.dispose();
	
		updateImage(f);
	}
}

